# -*- coding: utf-8 -*-
"""
PSA_HighVoltageIncrementor.py

Created on Wed Sep 04 13:44:24 2013

@author: Administrator
"""
import sys
import numpy as np
import PSA_HighVoltage
import time
import csv

def PSA_IncrementAll(arg):
    """ """
    comPorts = np.zeros(2)
    script, comPorts[0], comPorts[1], detectorSet, voltageIncrement = arg
    print comPorts
    print detectorSet
    voltageIncrement = int(voltageIncrement)
    
    print("Incrementing voltages by %d" %voltageIncrement)
    
    # create serial objects
    serials = []
    for (i, port) in enumerate(comPorts):
        serials.append(PSA_HighVoltage.HighVoltageDevice('PSA1', port))
    
    # Connect to serial devices
    for (i, port) in enumerate(comPorts):
        try:
            serials[i].Connect()
        except:
            print('Could not connect to COM%d' %port)
            return
    
    # Determine which is first HV device, which has 100 channels
    HVOrder = np.zeros(2).astype(int)
    (vm, vs, vp, c) = serials[0].ReadVoltages([81])
    if len(vm) == 0:
        # first serial device is the one 80 channels, the second HV device
        HVOrder[0] = 1
        HVOrder[1] = 0
    else:
        HVOrder[0] = 0
        HVOrder[1] = 1
    
    # which 
    if (detectorSet.lower() == 'fd'):
        print("Do nothing for now.  Add this stuff later.")
#    elif (detectorSet.lower() == 'zspec'):
    else:
        # First set the voltages for in the first HV device
        channelListList = []
        channelListList.append(np.arange(41, 101)) # 41 - 100, hv1
        channelListList.append(np.arange(1, 77, )) # 1 - 76 of hv2
        
        # Make containers for before and after voltage values
        vm_0 = np.zeros(136)
        vs_0 = np.zeros(136)
        vp_0 = np.zeros(136)
        c_0 = np.zeros(136)

        vm_1 = np.zeros(136)
        vs_1 = np.zeros(136)
        vp_1 = np.zeros(136)        
        c_1 = np.zeros(136)
        
        deviceNumber = np.zeros(136)
        deviceChNumber = np.zeros(136)
        
        # Read voltages before changing
        print("Reading voltages before incrementing...")
        (vm_0[0:len(channelListList[0])], vs_0[0:len(channelListList[0])], vp_0[0:len(channelListList[0])], c_0[0:len(channelListList[0])]) = \
            serials[HVOrder[0]].ReadVoltages(channelListList[0])
        (vm_0[60:137], vs_0[60:137], vp_0[60:137], c_0[60:137]) = serials[HVOrder[1]].ReadVoltages(channelListList[1])

        deviceNumber[0:len(channelListList[0])] = 0
        deviceNumber[60:137] = 1
        deviceChNumber[0:len(channelListList[0])] = channelListList[0]
        deviceChNumber[60:137] = channelListList[1]

        
        # print existing settings
        print('Before')        
        for i in xrange(136):
            print('%d\t%d\t%d\t%3.2f\t%3.2f\t%3.2f' %(i+1,deviceNumber[i], deviceChNumber[i], vs_0[i], vm_0[i], c_0[i]))

        # Increment voltages
        print("Incrementing voltages...")
        for i in xrange(2):
            serials[HVOrder[i]].IncrementVoltages(channelListList[i], voltageIncrement)
        print ("Finished incrementing voltages.  Wait for voltages to stabilize.")
        # wait a couple seconds for the voltages to settle down
        time.sleep(4)
        
        # Read voltages before changing
        print("Reading voltages before again...")
        (vm_1[0:len(channelListList[0])], vs_1[0:len(channelListList[0])], vp_1[0:len(channelListList[0])], c_1[0:len(channelListList[0])]) = \
            serials[HVOrder[0]].ReadVoltages(channelListList[0])
        (vm_1[60:137], vs_1[60:137], vp_1[60:137], c_1[60:137]) = serials[HVOrder[1]].ReadVoltages(channelListList[1])

        # print after settings
        print('After')
        for i in xrange(136):
            print('%d\t%d\t%d\t%3.2f\t%3.2f\t%3.2f' %(i+1,deviceNumber[i], deviceChNumber[i], vs_1[i], vm_1[i], c_1[i]))
        
    # write results to file
    filename = 'voltage_%s.txt' %(time.strftime('%Y%m%d_%H%M%S', time.localtime()))
    fid = open(filename, 'wb')
    csvWriterObj = csv.writer(fid, delimiter = ',')
    for i in xrange(len(vm_0)):
        lineOut = np.array([i+1, deviceNumber[i], deviceChNumber[i],  vs_0[i], vm_0[i], c_0[i], vs_1[i], vm_1[i], c_1[i]])
        csvWriterObj.writerow(lineOut)
    fid.close()
    print('Wrote %s' %filename)
    
if __name__ == "__main__":
    PSA_IncrementAll(sys.argv)